package org.example.jdbc;

import java.sql.*;
import java.util.Scanner;

public class JDBCReg {
    //实现注册功能 新建数据  写入数据库
    public static void main(String[] args) throws SQLException {
        try (Connection connection = DBUtil.getConnection()){
            Scanner sc= new Scanner(System.in);
            System.out.println("请输入注册用户名：");
            String username=sc.nextLine();
            Statement st= connection.createStatement();
            while(true){
                String sql= "SELECT username FROM user WHERE username=? ";
                PreparedStatement ps = connection.prepareStatement(sql);
                ps.setString(1, username);
                ResultSet rs = ps.executeQuery();
                if (rs.next()){
                    System.out.println("用户名重复请重新取一个:");
                    username=sc.nextLine();
                }else{
                    break;
                }


            }
            //不重名之后的
            System.out.print("请输入密码：");
            String password=sc.nextLine();
            System.out.println("请输入昵称");
            String nickname=sc.nextLine();
            System.out.println("请输入年龄");
            int age=sc.nextInt();
            String sql1= "INSERT INTO user(username,password,nickname,age)VALUES(?,?,?,?)";
            PreparedStatement ps1 = connection.prepareStatement(sql1);
            ps1.setString(1, username);
            ps1.setString(2, password);
            ps1.setString(3, nickname);
            ps1.setInt(4, age);
            ps1.executeUpdate();
            System.out.println("恭喜注册成功");

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }
}
